package com.gin.retrofit.interceptor

import com.gin.retrofit.annotation.StaticField
import com.gin.retrofit.annotation.StaticFields
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Response
import retrofit2.Invocation

/**
 * 静态表单参数拦截器
 * @author BX-Gin
 * @since 2024/2/29 10:31
 */
class StaticFieldInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        // 获取retrofit创建Request时在tag中保存的被调用的方法, 如果没获取到则直接返回
        val method = request.tag(Invocation::class.java)?.method() ?: return chain.proceed(request)
        // 获取请求体，如果不存在则直接返回
        val requestBody = request.body ?: return chain.proceed(request)

        val newRequestBuilder = request.newBuilder()

        if (requestBody is FormBody) {
            // 复制原表单数据
            val formBuilder = FormBody.Builder()
            for (i in 0 until requestBody.size) {
                formBuilder.addEncoded(requestBody.encodedName(i), requestBody.encodedValue(i))
            }
            // 添加注解上的静态参数
            val annotations = findAnnotations(method.annotations)
            for (staticField in annotations) {
                formBuilder.add(staticField.key, staticField.value)
            }
            newRequestBuilder.post(formBuilder.build())
        }
        return chain.proceed(newRequestBuilder.build())
    }

    companion object {
        @JvmStatic
        fun findAnnotations(annotations: Array<Annotation>): List<StaticField> {
            val list = ArrayList<StaticField>()

            for (annotation in annotations) {
                if (annotation is StaticField) {
                    list.add(annotation)
                }
                if (annotation is StaticFields) {
                    list.addAll(annotation.value.toList())
                }
            }
            return list
        }
    }
}